package com.wing.order.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.CodeUtil;
import com.wing.common.utils.HttpHelper;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.Result;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.response.ProductDetailVO;
import com.wing.order.dao.DynamicDao;
import com.wing.order.dao.InventoryOutPlanDao;
import com.wing.order.dao.InventoryOutPlanDetailDao;
import com.wing.order.model.entity.InventoryOutPlan;
import com.wing.order.model.entity.InventoryOutPlanDetail;
import com.wing.order.model.request.InventoryOutPlanForm;
import com.wing.order.model.response.InventoryInoutJobVO;
import com.wing.order.model.response.InventoryOutPlanDetailVO;
import com.wing.order.model.response.InventoryOutPlanVO;
import com.wing.platform.feign.PlatformClient;
import com.wing.warehouse.dao.WarehouseDao;
import com.wing.warehouse.model.entity.Warehouse;
import com.wing.warehouse.model.entity.WarehouseInventoryType;
import com.wing.warehouse.model.response.WarehouseVO;
import com.wing.warehouse.service.WarehouseAreaService;
import com.wing.warehouse.service.WarehouseInventoryTypeService;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 出库单计划-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class InventoryOutPlanServiceImpl extends ServiceImpl<InventoryOutPlanDao, InventoryOutPlan> implements InventoryOutPlanService {
    @Value("${platform.gatewayUrl}")
    private String gatewayUrl;
    @Autowired
    InventoryOutPlanDao inventoryOutPlanDao;
    @Autowired
    InventoryOutPlanDetailDao inventoryOutPlanDetailDao;
    @Autowired
    private DynamicDao dynamicDao;
    @Autowired
    private EnterpriseClient productDetailClient;
    @Autowired
    private PlatformClient platformClient;
    @Autowired
    private WarehouseInventoryTypeService warehouseInventoryTypeService;
    @Autowired
    private WarehouseAreaService warehouseAreaService;
    @Autowired
    private InventoryOutPlanDetailService inventoryOutPlanDetailService;
    @Autowired
    private WarehouseDao warehouseDao;
    @Transactional
    @Override
    public JsonResult add(InventoryOutPlanForm inventoryOutPlanForm) {
        String loginUsername = JwtUtils.getLoginUsername();
        //校验
        InventoryOutPlan inventoryOutPlan =new InventoryOutPlan();
        inventoryOutPlanForm.setConsigner(loginUsername);
        //出库类型是调拨到云仓 查询平台端仓库，仓库库区
        QueryWrapper<WarehouseInventoryType> typeWrapper = new QueryWrapper<>();
        typeWrapper.eq("code",inventoryOutPlanForm.getInoutTypeCode());
        WarehouseInventoryType inventoryType = warehouseInventoryTypeService.getOne(typeWrapper);
        if (inventoryType.getCode().equals("allotCloudWarehouse")) {
            JsonResult<com.wing.platform.order.model.response.WarehouseVO> areaJsonResult = platformClient.getWarehouseById(inventoryOutPlanForm.getInWarehouseId());
            inventoryOutPlanForm.setInAreaName(areaJsonResult.getData().getAddr());
        }else{
            if (inventoryOutPlanForm.getInWarehouseId()!=null&&inventoryOutPlanForm.getInWarehouseId()!=0){
                WarehouseVO warehouseVO = warehouseDao.get4appById(inventoryOutPlanForm.getInWarehouseId());
                inventoryOutPlanForm.setInAreaName(warehouseVO.getAddr());
            }

        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String today = format.format(new Date());//getDayMaxNo
        Integer maxCode = dynamicDao.getDayMaxNo("ord_inventory_out_plan");
        String maxNo = CodeUtil.getCode(maxCode);
        inventoryOutPlanForm.setCode("P" + today + maxNo);
        inventoryOutPlanForm.setNo(Integer.valueOf(maxNo));
        inventoryOutPlanForm.setDay(Integer.valueOf(today));
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(InventoryOutPlan.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(inventoryOutPlanForm, inventoryOutPlan, copyOptions);
        baseMapper.insert(inventoryOutPlan);
        //出库单计划明细
        JSONArray jsonArray = JSONArray.parseArray(inventoryOutPlanForm.getProductJson());
        for (int i = 0; i < jsonArray.size(); i++) {
            InventoryOutPlanDetail inventoryOutPlanDetail = new InventoryOutPlanDetail();
            inventoryOutPlanDetail.setPlanId(inventoryOutPlan.getId());
            JSONObject obj = (JSONObject) jsonArray.get(i);
            String skuCode = obj.getString("skuCode");
            JsonResult<ProductDetailVO> productJson = productDetailClient.getProductDetailBySkuCode(skuCode);
            String productPic = obj.getString("productPic");
            String productName = obj.getString("skuName");
            String skuSpecCode = obj.getString("skuSpecValueNames");
            String unitName = obj.getString("unitName");
            //Long unitId = Long.parseLong(obj.getString("unitId"));
            Long quantity = Long.parseLong(obj.getString("quantity"));
            String enterpriceCode = obj.getString("enterpriceCode");
            String barcode = obj.getString("barcode");
            String supplyPrice = obj.getString("supplyPrice");
            String marketPrice = obj.getString("marketPrice");
            String productTypeName = obj.getString("productTypeName");
            inventoryOutPlanDetail.setSkuCode(skuCode);
            inventoryOutPlanDetail.setSkuPic(productPic);
            inventoryOutPlanDetail.setProductName(productName);
            inventoryOutPlanDetail.setSkuSpecCode(skuSpecCode);
            inventoryOutPlanDetail.setUnitName(unitName);
            inventoryOutPlanDetail.setProductTypeName(productTypeName);
            //inventoryOutPlanDetail.setUnitId(unitId);
            inventoryOutPlanDetail.setQuantity(quantity);
            inventoryOutPlanDetail.setEnterpriceCode(enterpriceCode);
            inventoryOutPlanDetail.setBarcode(barcode);
            inventoryOutPlanDetail.setSupplyPrice(new BigDecimal(supplyPrice));
            inventoryOutPlanDetail.setMarketPrice(new BigDecimal(marketPrice));

            inventoryOutPlanDetailDao.insert(inventoryOutPlanDetail);
        }

        return JsonResult.success("操作成功");
    }

    @Override
    public List<InventoryOutPlanVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<InventoryOutPlanVO> pageList4app(Page page, Map<String, Object> params) {
        List<InventoryOutPlanVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public InventoryOutPlanVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public IPage<InventoryOutPlan> getInventoryOutPlanPageList(InventoryOutPlan inventoryOutPlan, Integer page, Integer limit) {
        IPage<InventoryOutPlan> iPage = new Page<InventoryOutPlan>(page, limit);
        QueryWrapper<InventoryOutPlan> wrapper = new QueryWrapper<>();
        if(inventoryOutPlan.getOutWarehouseId()!=null){
            wrapper.eq("p.out_warehouse_id", inventoryOutPlan.getOutWarehouseId());
        }
        if(inventoryOutPlan.getInWarehouseId()!=null){
            wrapper.eq("p.in_warehouse_id", inventoryOutPlan.getInWarehouseId());
        }
        if(StringUtils.isNotEmpty(inventoryOutPlan.getCode())){
            wrapper.and(qw -> qw.like("p.code",inventoryOutPlan.getCode()));
        }
        wrapper.gt(StringUtils.isNotBlank(inventoryOutPlan.getStartCreateTime()),"p.create_time", inventoryOutPlan.getStartCreateTime());
        wrapper.le(StringUtils.isNotBlank(inventoryOutPlan.getEndCreateTime()),"p.create_time", inventoryOutPlan.getEndCreateTime());

        if(StringUtils.isNotEmpty(inventoryOutPlan.getInoutTypeCode())){
            wrapper.eq("p.inout_type_code", inventoryOutPlan.getInoutTypeCode());
        }
        if(inventoryOutPlan.getStatus()!=null){
            wrapper.eq("p.status", inventoryOutPlan.getStatus().getValue());
        }
        wrapper.orderByDesc("p.create_time");
        inventoryOutPlanDao.getInventoryOutPlanPageList(iPage,wrapper);
        return iPage;
    }

    @Override
    public InventoryOutPlanVO getInventoryOutPlanById(Long id) {
        return inventoryOutPlanDao.getInventoryOutPlanById(id);
    }

    @Override
    public List<InventoryOutPlan> getPlanAll() {
        QueryWrapper<InventoryOutPlan> wrapper = new QueryWrapper<>();
        wrapper.select("id","code");
        return inventoryOutPlanDao.selectList(wrapper);
    }

    @Override
    public IPage<InventoryInoutJobVO> getInventoryOutWorkRecordPageList(InventoryInoutJobVO inventoryInoutJobVO, Integer page, Integer limit) {
        IPage<InventoryInoutJobVO> iPage = new Page<InventoryInoutJobVO>(page, limit);
        QueryWrapper<InventoryInoutJobVO> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(inventoryInoutJobVO.getInoutTypeCode())){
            wrapper.eq("job.inout_type_code", inventoryInoutJobVO.getInoutTypeCode());
        }
        if(StringUtils.isNotEmpty(inventoryInoutJobVO.getCode())){
            wrapper.and(qw -> qw.like("job.code",inventoryInoutJobVO.getCode()));
        }
        if(StringUtils.isNotEmpty(inventoryInoutJobVO.getPlanCode())){
            wrapper.and(qw -> qw.like("job.plan_code",inventoryInoutJobVO.getPlanCode()));
        }
        if(inventoryInoutJobVO.getOutWarehouseId()!=null){
            wrapper.eq("op.out_warehouse_id", inventoryInoutJobVO.getOutWarehouseId());
        }
        if(inventoryInoutJobVO.getInWarehouseId()!=null){
            wrapper.eq("op.in_warehouse_id", inventoryInoutJobVO.getInWarehouseId());
        }
        if(StringUtils.isNotBlank(inventoryInoutJobVO.getStartCreateTime())){
            wrapper.gt("job.create_time", inventoryInoutJobVO.getStartCreateTime());
        }
        if(StringUtils.isNotBlank(inventoryInoutJobVO.getEndCreateTime())){
            wrapper.le("job.create_time", inventoryInoutJobVO.getEndCreateTime());
        }
        wrapper.eq("job.inout_type",2);
        wrapper.orderByDesc("job.create_time");
        inventoryOutPlanDao.getInventoryOutWorkRecordPageList(iPage,wrapper);
        return iPage;
    }

    @Override
    public List<Warehouse> getPlatformWarehouseAll() {
        final String reqUri = gatewayUrl + "platformWarehouse/warehouse/admin/warehouse/getAll";
        try {
            String tokenJson = HttpHelper.httpGet(reqUri);
            JSONObject jsonObject = JSONObject.parseObject(tokenJson);
            String data = jsonObject.getString("data");
            List<Warehouse> list =  JSONObject.parseArray(data,Warehouse.class);
            return list;
            //out.println(String.format("==========================>this is response:{%s}", tokenJson));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public InventoryOutPlanVO getInventoryOutPlanDetailById(Long id) {
        List<InventoryOutPlanDetailVO> inventoryOutPlanDetailList = inventoryOutPlanDetailService.getInventoryOutPlanDetailVOList(id);
        InventoryOutPlanVO inventory = inventoryOutPlanDao.getInventoryOutPlanById(id);
        inventory.setProductDetailList(inventoryOutPlanDetailList);
        return inventory;
    }

}
